package com.group.common.utils;

import com.group.neps.entity.Province;

import java.io.*;
import java.util.HashMap;

/**
 * @author 刘海翔
 * @version 1.0
 */
public class LocationSaver {

    /**
     * 从指定路径加载省份和城市数据，并将完整结构序列化存储到目标文件
     *
     * @param provinceFilePath 省份 JSON 文件路径
     * @param cityFilePath     城市 JSON 文件路径
     * @param outputFilePath   输出序列化文件的路径
     */
    public static void saveLocationMap(String provinceFilePath, String cityFilePath, String outputFilePath) {
        try {
            HashMap<String, Province> provinceMap = ProvinceLoader.loadProvinces(provinceFilePath);
            CityLoader.loadCities(provinceMap, cityFilePath);
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outputFilePath))) {
                oos.writeObject(provinceMap);
                System.out.println("地理位置数据已成功保存到: " + outputFilePath);
            }

        } catch (IOException e) {
            System.err.println("保存地理位置数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * 从指定路径加载省份和城市数据，构建名称到编码的反向映射，并序列化存储到目标文件
     *
     * @param provinceFilePath 省份 JSON 文件路径
     * @param cityFilePath     城市 JSON 文件路径
     * @param outputFilePath   输出序列化文件的路径
     */
    public static void saveLocationReverseMap(String provinceFilePath, String cityFilePath, String outputFilePath) {
        try {
            HashMap<String, String> provinceReverseMap = ProvinceLoader.loadProvincesReverse(provinceFilePath);
            HashMap<String, String> cityReverseMap = CityLoader.loadCitiesReverse(cityFilePath);
            HashMap<String, HashMap<String, String>> locationReverseMap = new HashMap<>();

            for (String provinceName : provinceReverseMap.keySet()) {
                String provinceCode = provinceReverseMap.get(provinceName);
                HashMap<String, String> citiesInProvince = new HashMap<>();

                for (String cityName : cityReverseMap.keySet()) {
                    String fullCityCode = cityReverseMap.get(cityName);
                    if (fullCityCode.startsWith(provinceCode)) {
                        citiesInProvince.put(cityName, fullCityCode);
                    }
                }

                if (!citiesInProvince.isEmpty()) {
                    locationReverseMap.put(provinceName, citiesInProvince);
                }
            }
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outputFilePath))) {
                oos.writeObject(locationReverseMap);
                System.out.println("地理位置反向数据已成功保存到: " + outputFilePath);
            }
        } catch (IOException e) {
            System.err.println("保存地理位置反向数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

